package com.rimi.filter;

import com.rimi.bean.UserBean;
import com.rimi.service.UserService;
import com.rimi.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class Filter2_RememberMeFilter implements Filter {

    private UserService userService;

    public Filter2_RememberMeFilter(){
        userService=new UserServiceImpl();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取该用户的cookie
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Cookie[] cookies = request.getCookies();

        if(cookies!=null){
            for (Cookie cookie : cookies) {
                //找到我们存储的记住密码的cookie
                if("rememberMe".equals(cookie.getName())){
                    String token = cookie.getValue();
                    //使用token去数据库查询用户信息
                    UserBean user = userService.getUserByToken(token);
                    if(user!=null){
                        //将用户信息存储到session中
                        request.getSession().setAttribute("user",user);

                    }
                }
            }
        }

        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
